<script setup>
import {useRouter} from 'vue-router'
import {ref, onBeforeMount} from 'vue'
import {ADD_ADDRESS_ROUTE} from "@/router/routes/address/AddAddress.js";
import {getAddressAPI} from "@/api/address.js";
import {EDITOR_ADDRESS_ROUTE} from "@/router/routes/address/EditorAddress.js";

const router = useRouter()

const goBack = () => {
  router.back()
}

const goAddAddress = () => {
  router.push({name: ADD_ADDRESS_ROUTE})
}

const list = ref([])
onBeforeMount(async () => {
  list.value = (await getAddressAPI()).map(
      item => ({
        id: item.id,
        name: item.name,
        tel: item.phone,
        isDefault: item.idDefault,
        address: item.province + item.city + item.county + item.address,
      })
  )
  let defaultAddress = null;
  list.value = list.value.filter(item => {
    if (item.isDefault) {
      defaultAddress = item;
      return false;
    }
    return item.isDefault === false;
  })
  if (defaultAddress !== null) list.value.unshift(defaultAddress)
})

const onEdit = (item, index) => {
  router.push({name: EDITOR_ADDRESS_ROUTE, query: {id: item.id}})
}
</script>

<template>
  <div class="address-list">
    <van-nav-bar
        fixed
        placeholder
        title="收货地址列表"
        left-text="返回"
        left-arrow
        @click-left="goBack"
        right-text="新增"
        @click-right="goAddAddress"
    />
    <van-address-list
        :list="list"
        :show-add-button="false"
        :switchable="false"
        default-tag-text="默认"
        @edit="onEdit"
    />
  </div>
</template>

<style scoped lang="scss">

</style>